﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EquipmentConfig.Class;
using System.Threading;

namespace EquipmentConfig
{
    public partial class WaterLevelSetting : Form
    {
        private MainForm mf;

        public WaterLevelSetting(MainForm mainForm)
        {
            InitializeComponent();
            mf = mainForm;
        }

        public void InitValue(byte[] recData)
        {
            this.Invoke((MethodInvoker)delegate
            {
                if (recData.Length >= 120)
                {
                    List<byte> listData = recData.ToList<byte>();
                    SetValue(listData, txtWater1, 0, 4);
                    SetValue(listData, txtFlow1, 4, 8);
                    SetValue(listData, txtWater2, 12, 4);
                    SetValue(listData, txtFlow2, 16, 8);
                    SetValue(listData, txtWater3, 24, 4);
                    SetValue(listData, txtFlow3, 28, 8);
                    SetValue(listData, txtWater4, 36, 4);
                    SetValue(listData, txtFlow4, 40, 8);
                    SetValue(listData, txtWater5, 48, 4);
                    SetValue(listData, txtFlow5, 52, 8);
                    SetValue(listData, txtWater6, 60, 4);
                    SetValue(listData, txtFlow6, 64, 8);
                    SetValue(listData, txtWater7, 72, 4);
                    SetValue(listData, txtFlow7, 76, 8);
                    SetValue(listData, txtWater8, 84, 4);
                    SetValue(listData, txtFlow8, 88, 8);
                    SetValue(listData, txtWater9, 96, 4);
                    SetValue(listData, txtFlow9, 100, 8);
                    SetValue(listData, txtWater10, 108, 4);
                    SetValue(listData, txtFlow10, 112, 8);
                }
            });
        }

        public void SetValue(List<byte> listData, TextBox tb, int index, int count)
        {
            List<byte> listValue = listData.GetRange(index, count);
            if (listValue.Where(x => x == 0xFF).Count() != count)
            {
                if (count == 4)
                {
                    tb.Text = (BitConverter.ToUInt32(listValue.Reverse<byte>().ToArray(), 0) / 1000.0).ToString();
                }

                if (count == 8)
                {
                    tb.Text = (BitConverter.ToUInt64(listValue.Reverse<byte>().ToArray(), 0) / 100000.0).ToString();
                }
            }
            else
            {
                tb.Text = string.Empty;
            }
        }

        public bool GetValue(List<byte> listValue, TextBox tb1, TextBox tb2, ref int count)
        {
            if (tb1.Text != string.Empty && tb2.Text != string.Empty)
            {
                listValue.AddRange(BitConverter.GetBytes(tb1.Text.ToString().IndexOf('.') > 0 ? Convert.ToUInt32(Convert.ToDecimal(tb1.Text.ToString()) * 1000) : Convert.ToUInt32(tb1.Text.ToString()) * 1000).Reverse<byte>().ToArray());
                listValue.AddRange(BitConverter.GetBytes(tb2.Text.ToString().IndexOf('.') > 0 ? Convert.ToUInt64(Convert.ToDecimal(tb2.Text.ToString()) * 100000) : Convert.ToUInt64(tb2.Text.ToString()) * 100000).Reverse<byte>().ToArray());
                count += 1;
                return true;
            }
            else
            {
                if (tb1.Text == string.Empty && tb2.Text == string.Empty)
                {
                    listValue.AddRange(new byte[12] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF });
                    return true;
                }
                else
                {
                    if (tb1.Text == string.Empty)
                    {
                        Messages.ShowAlertDialog(string.Format("请输入水位{0}！", tb1.Name.Substring(tb1.Name.Length -1,1)), false);
                    }

                    if (tb2.Text == string.Empty)
                    {
                        Messages.ShowAlertDialog(string.Format("请输入瞬时流量{0}！", tb2.Name.Substring(tb2.Name.Length - 1, 1)), false);
                    }
                    return false;
                }
            }
        }

        private void txtBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            TextBox tb = (TextBox)sender;
            if (e.KeyChar != 8)// 允许输入退格键
            {
                // 允许输入数字、小数点  
                if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != (char)('.'))
                {
                    e.Handled = true;
                }
                else
                {
                    if (tb.SelectionLength > 0)
                    {
                        e.Handled = true;
                    }
                }

                // 小数点只能输入一次  
                if (e.KeyChar == (char)('.') && tb.Text.IndexOf('.') != -1)
                {
                    e.Handled = true;
                }

                // 第一位不能为小数点  
                if (e.KeyChar == (char)('.') && tb.Text == "")
                {
                    e.Handled = true;
                }

                // 第一位是0，第二位必须为小数点  
                if (e.KeyChar != (char)('.') && tb.Text == "0")
                {
                    e.Handled = true;
                }

                // 有小数只保留3位
                if (tb.Text.IndexOf('.') != -1)
                {
                    if (tb.Text.Length - tb.Text.IndexOf('.') - 1 == 3)
                    {
                        e.Handled = true;
                    }
                }
            }
        }

        private void txtBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            TextBox tb = (TextBox)sender;
            if (e.KeyChar != 8)// 允许输入退格键
            {
                // 允许输入数字、小数点  
                if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != (char)('.'))
                {
                    e.Handled = true;
                }
                else
                {
                    if (tb.SelectionLength > 0)
                    {
                        e.Handled = true;
                    }
                }

                // 小数点只能输入一次  
                if (e.KeyChar == (char)('.') && tb.Text.IndexOf('.') != -1)
                {
                    e.Handled = true;
                }

                // 第一位不能为小数点  
                if (e.KeyChar == (char)('.') && tb.Text == "")
                {
                    e.Handled = true;
                }

                // 第一位是0，第二位必须为小数点  
                if (e.KeyChar != (char)('.') && tb.Text == "0")
                {
                    e.Handled = true;
                }

                // 有小数只保留5位
                if (tb.Text.IndexOf('.') != -1)
                {
                    if (tb.Text.Length - tb.Text.IndexOf('.') - 1 == 5)
                    {
                        e.Handled = true;
                    }
                }
            }
        }

        /// <summary>
        /// 读取
        /// </summary>
        private void btnRead_Click(object sender, EventArgs e)
        {
            try
            {
                mf.timer2.Enabled = false;
                mf.recBuffer.Clear();
                MainForm.isSuccess = false;
                mf.SendCmd(Protocol.GetWriteDeviceCmd(0x11, new byte[1] { 0x00 }));
                Thread sub = new Thread(() =>
                {
                    if (!mf.CheckReturnCmd())
                    {
                        Messages.ShowAlertDialog("读取水位流量标定失败！", false);
                    }
                });
                sub.IsBackground = true;
                sub.Start();
                mf.timer2.Enabled = true;
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("读取水位流量标定错误！", ex);
            }
        }

        /// <summary>
        /// 写入
        /// </summary>
        private void btnWrite_Click(object sender, EventArgs e)
        {
            try
            {
                int intCount = 0;
                List<byte> listData = new List<byte>();
                if (!GetValue(listData, txtWater1, txtFlow1, ref intCount))
                {
                    return;
                }

                if (!GetValue(listData, txtWater2, txtFlow2, ref intCount))
                {
                    return;
                }

                if (!GetValue(listData, txtWater3, txtFlow3, ref intCount))
                {
                    return;
                }

                if (!GetValue(listData, txtWater4, txtFlow4, ref intCount))
                {
                    return;
                }

                if (!GetValue(listData, txtWater5, txtFlow5, ref intCount))
                {
                    return;
                }

                if (!GetValue(listData, txtWater6, txtFlow6, ref intCount))
                {
                    return;
                }

                if (!GetValue(listData, txtWater7, txtFlow7, ref intCount))
                {
                    return;
                }

                if (!GetValue(listData, txtWater8, txtFlow8, ref intCount))
                {
                    return;
                }

                if (!GetValue(listData, txtWater9, txtFlow9, ref intCount))
                {
                    return;
                }

                if (!GetValue(listData, txtWater10, txtFlow10, ref intCount))
                {
                    return;
                }

                mf.timer2.Enabled = false;
                mf.recBuffer.Clear();
                listData.Insert(0, Convert.ToByte(intCount));
                MainForm.isSuccess = false;
                mf.SendCmd(Protocol.GetWriteDeviceCmd(0x12, listData.ToArray()));
                Thread sub = new Thread(() =>
                {
                    if (!mf.CheckReturnCmd())
                    {
                        Messages.ShowAlertDialog("写入水位流量标定失败！", false);
                    }
                });
                sub.IsBackground = true;
                sub.Start();
                mf.timer2.Enabled = true;
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("写入水位流量标定错误！", ex);
            }
        }

        private void WaterLevelSetting_FormClosing(object sender, FormClosingEventArgs e)
        {
            mf.timer2.Enabled = true;
            this.Dispose();
        }
    }
}
